package newApi;

import java.util.*;

class Employee {
    private String name;

    public Employee(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

class Company {
    private String name;
    private List<Employee> employees;

    public Company(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<Employee> getEmployees() {
        return employees;
    }

    public void setEmployees(List<Employee> employees) {
        this.employees = employees;
    }
}


public class OptionalTest {
    public static void main(String[] args) {
        Optional<String> optional = Optional.of("hello");

        if (optional.isPresent()) {
            System.out.println(optional.get());
        }

        HashMap<String, Object> userInfo = new HashMap<String, Object>() {{
            put("age", 23);
            put("name", "毛毛");
        }};


        // 简化上面的写法
        // 1、ifPresent如果Optional为空什么都不做，否则把Optional里的值应用于Consumer
        optional.ifPresent(value -> System.out.println(value));
        System.out.println(optional.orElse("hello")); // 如果存在则返回，不存在使用指定值other返回
        System.out.println(optional.orElseGet(() -> new String("hello"))); // 如果存在，则返回，不存在，则调用供应商获取

        /**
         * ofNullable：如果p是个null，则返回一个空的Optional，否则返回一个包装了p的Optional
         * orElseGet：如果当前Optional里有值，则返回该值，否则使用供应商提供的返回结果
         */
        Person p = null;
        int age = Optional.ofNullable(p).orElseGet(() -> new Person(23, "毛毛")).getAge();
        System.out.println(age);


        /**
         * 一个关于Optional的真实案例：
         * 如果一个集合不为空返回这个集合，否则返回一个空的集合。
         */
        Employee employee1 = new Employee("mao");
        Employee employee2 = new Employee("ke");

//        Company company = null;
        Company company = new Company("wonders");
        List<Employee> employees = Arrays.asList(employee1, employee2);
        company.setEmployees(employees);

        // company为空最终返回一个空的集合，company不为空，若employees为空，也返回一个空的集合，若employees也不为空，则返回employees
        Optional<Company> companyOption = Optional.ofNullable(company);
        System.out.println(companyOption.map((company1 -> company1.getEmployees())).orElse(Collections.emptyList()));

        // company.getEmployees()不为空则直接返回集合，为空返回空集合
//        Optional.ofNullable(company.getEmployees()).orElse(Collections.emptyList());

    }
}
